﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Core.Infrastructure.CommandExtensions
{
    public class ControlLoaded
    {
        private static readonly DependencyProperty ControlLoadedProperty = DependencyProperty.RegisterAttached(
            "ControlLoaded",
            typeof(ControlLoadedCommandBehavior),
            typeof(ControlLoaded),
            null);

        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
            "Command",
            typeof(ICommand),
            typeof(ControlLoaded),
            new PropertyMetadata(OnSetCommandCallback));

        public static void SetCommand(Control control, ICommand command)
        {
            control.SetValue(CommandProperty, command);
        }

        public static ICommand GetCommand(Control control)
        {
            return control.GetValue(CommandProperty) as ICommand;
        }

        private static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var control = dependencyObject as Control;
            if (control != null)
                GetOrCreateBehavior(control).Command = e.NewValue as ICommand;
        }

        private static ControlLoadedCommandBehavior GetOrCreateBehavior(Control control)
        {
            var behavior = control.GetValue(ControlLoadedProperty) as ControlLoadedCommandBehavior;
            if (behavior == null)
            {
                behavior = new ControlLoadedCommandBehavior(control);
                control.SetValue(ControlLoadedProperty, behavior);
            }

            return behavior;
        }
        
    }
}
